package com.ruoyi.web.controller.commerce;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.commerce.domain.bo.CommercePurchaseBo;
import com.ruoyi.commerce.domain.vo.CommerceOrdersVo;
import com.ruoyi.commerce.domain.vo.CommerceProductsVo;
import com.ruoyi.commerce.domain.vo.CommercePurchaseVo;
import com.ruoyi.commerce.service.ICommerceOrdersService;
import com.ruoyi.commerce.service.ICommerceProductsService;
import com.ruoyi.commerce.service.ICommercePurchaseService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 采购单
 *
 * @author ruoyi
 * @date 2024-01-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/commerce/purchase")
public class CommercePurchaseController extends BaseController {

    private final ICommercePurchaseService iCommercePurchaseService;
    private final ICommerceOrdersService iCommerceOrdersService;
    private final ICommerceProductsService iCommerceProductsService;

    /**
     * 查询采购单列表
     */
    @SaCheckPermission("commerce:purchase:list")
    @GetMapping("/list")
    public TableDataInfo<CommercePurchaseVo> list(CommercePurchaseBo bo, PageQuery pageQuery) {
        return iCommercePurchaseService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出全部采购单列表
     */
    @SaCheckPermission("commerce:purchase:export")
    @Log(title = "采购单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAll")
    public void exportAll(CommercePurchaseBo bo, HttpServletResponse response) {
        List<CommercePurchaseVo> list = iCommercePurchaseService.queryList(bo);
        ExcelUtil.exportExcel(list, "采购单", CommercePurchaseVo.class, response);
    }

    /**
     * 导出选择采购单列表
     */
    @SaCheckPermission("commerce:purchase:export")
    @Log(title = "采购单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelect/{purchaseIds}")
    public void exportSelect(@NotEmpty(message = "主键不能为空") @PathVariable Collection<Long> purchaseIds,
                             HttpServletResponse response) {
        List<CommercePurchaseVo> purchaseVolist = iCommercePurchaseService.queryByIds(purchaseIds);
        List<CommerceOrdersVo> list = new ArrayList<>();

        purchaseVolist.forEach(item -> {
            List<CommerceOrdersVo> ordersVos = iCommerceOrdersService.queryListByPurchaseId(item.getPurchaseId());
            ordersVos.forEach(order->{
                CommerceProductsVo productsVo = iCommerceProductsService.queryById(order.getProductId());
                order.setProductName(productsVo.getProductName());
            });
            list.addAll(ordersVos);
        });

        ExcelUtil.exportExcel(list, "采购清单", CommerceOrdersVo.class, response);
    }

    /**
     * 获取采购单详细信息
     *
     * @param purchaseId 主键
     */
    @SaCheckPermission("commerce:purchase:query")
    @GetMapping("/{purchaseId}")
    public R<CommercePurchaseVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long purchaseId) {
        CommercePurchaseVo vo = iCommercePurchaseService.queryById(purchaseId);
        List<CommerceOrdersVo> ordersVos = iCommerceOrdersService.queryListByPurchaseId(purchaseId);
        ordersVos.forEach(order->{
            CommerceProductsVo productsVo = iCommerceProductsService.queryById(order.getProductId());
            order.setProductName(productsVo.getProductName());
        });
        vo.setOrdersVoList(ordersVos);
        return R.ok(vo);
    }

    /**
     * 新增采购单
     */
    @SaCheckPermission("commerce:purchase:add")
    @Log(title = "采购单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CommercePurchaseBo bo) {
        CommercePurchaseBo resultBo = iCommercePurchaseService.insertByBo(bo);
        Map<String, Object> updates = new HashMap<>();
        updates.put("purchase_id", resultBo.getPurchaseId());
        updates.put("status", resultBo.getStatus());
        return toAjax(iCommerceOrdersService.batchUpdateOrderInfo(bo.getOrderIds(), updates));
    }

    /**
     * 修改采购单
     */
    @SaCheckPermission("commerce:purchase:edit")
    @Log(title = "采购单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CommercePurchaseBo bo) {
        iCommercePurchaseService.updateByBo(bo);
        List<CommerceOrdersVo> ordersVos = iCommerceOrdersService.queryListByPurchaseId(bo.getPurchaseId());
        Collection<Long> orderIds = new ArrayList<>();
        for (CommerceOrdersVo order : ordersVos) {
            orderIds.add(order.getId());
        }
        Map<String, Object> updates = new HashMap<>();
        updates.put("status", bo.getStatus());
        return toAjax(iCommerceOrdersService.batchUpdateOrderInfo(orderIds, updates));
    }

    /**
     * 删除采购单
     *
     * @param purchaseIds 主键串
     */
    @SaCheckPermission("commerce:purchase:remove")
    @Log(title = "采购单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{purchaseIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] purchaseIds) {
        return toAjax(iCommercePurchaseService.deleteWithValidByIds(Arrays.asList(purchaseIds), true));
    }
}
